package org.duang.event;

import java.lang.reflect.Type;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.duang.event.core.DuangEvent;
import org.duang.event.core.DuangEventListener;
import org.duang.kit.MultiMaps;
import org.duang.kit.ToolsKit;

@SuppressWarnings("rawtypes")
public class EventHandler {
	
	private final MultiMaps<Type, DuangEventListener> map;
	private final ExecutorService pool;
	private final int nThreads = 10;
	
	public EventHandler(MultiMaps<Type, DuangEventListener> map, ExecutorService pool) {
		super();
		this.map = map;
		this.pool = pool;
	}
	
//	public EventHandler(DuangEvent event, DuangEventListener listener) {
//		MultiMaps<Type, DuangEventListener> map = new MultiMaps<Type, DuangEventListener>();
//		map.put(event.getClass(), listener);
//		this.map = map;
//		this.pool = Executors.newFixedThreadPool(nThreads);
//	}
	
	@SuppressWarnings("unchecked")
	public void executeEvent(final DuangEvent event){
		List<DuangEventListener> list = map.get(event.getClass());
		for(Iterator<DuangEventListener> it = list.iterator(); it.hasNext();){
			final DuangEventListener listener = it.next();
			if(ToolsKit.isNotEmpty(pool)){
				pool.execute(new Runnable(){
					public void run() {
						listener.onEvent(event);
					}
				});
			} else {
				listener.onEvent(event);
			}
		}
	}
}
